package com.bjpowernode.boss.mvc.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bjpowernode.boss.common.constant.SysConstans;
import com.bjpowernode.boss.common.enums.ResponseCode;
import com.bjpowernode.boss.convert.UserConvert;
import com.bjpowernode.boss.dao.entity.UserInfo;
import com.bjpowernode.boss.mvc.models.AjaxResult;
import com.bjpowernode.boss.mvc.models.form.user.UserEditForm;
import com.bjpowernode.boss.mvc.models.pages.PageInfo;
import com.bjpowernode.boss.mvc.models.vo.user.UserInfoVo;
import com.bjpowernode.boss.mvc.service.UserService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yu
 * @date 2024/7/8  22:52
 */
@CrossOrigin
@RequestMapping("/user")
@RestController
public class UserController extends BaseController{

    @Resource
    UserConvert userConvert ;

    @Resource
    private UserService userService ;

    /**
     * 分页查询商户
     *
     * @param pageNo
     * @return
     */
    @GetMapping("/pageList")
    public AjaxResult pageList(Integer pageNo) {
        pageNo = defPageNo(pageNo) ;
        IPage<UserInfo> pageResult = userService.pageList(pageNo, SysConstans.PAGE_SIZE) ;
        // 总页数:
        long totalPage = pageResult.getPages() ;
        // 分页查询的记录
        List<UserInfo> userInfoList = pageResult.getRecords() ;

        // 创建分页对象
        PageInfo pageInfo = new PageInfo(pageResult.getCurrent(), totalPage) ;

        // 包装发给前端的数据
        Map<String, Object> data = new HashMap<>() ;
        data.put("pageInfo", pageInfo) ;
        data.put("list", userConvert.toListUserInfoVo(userInfoList)) ;

        return AjaxResult.OK(data) ;
    }

    @GetMapping("/{userId}")
    public AjaxResult getUserById(@PathVariable(value = "userId") String userId) {
        if (StrUtil.isNotBlank(userId)) {
            UserInfoVo userInfoVo = userService.getUserById(userId) ;
            return AjaxResult.OK(userInfoVo) ;
        }

        return AjaxResult.FAIL(ResponseCode.REQUEST_PARAM_ERR) ;
    }

    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody @Valid UserEditForm userEditForm) {
        int edit = userService.editUser(userEditForm) ;
        return edit >= 1 ? AjaxResult.OK() : AjaxResult.FAIL() ;
    }

    @PostMapping("/editStatus")
    public AjaxResult editStatus(@RequestParam String userId) {
        int edit = userService.editStatusById(userId) ;
        return edit >= 1 ? AjaxResult.OK() : AjaxResult.FAIL() ;
    }
}
